package vboot.core.module.sys.api.role;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import vboot.core.common.mvc.dao.JdbcDao;
import vboot.core.common.mvc.dao.Sqler;
import vboot.core.common.mvc.api.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import vboot.core.module.sys.org.root.UserCacheService;

@RestController
@RequestMapping("sys/api/role")
@Api(tags = {"接口管理-接口角色"})
public class SysApiRoleApi {
    private String table = "sys_api_role";

    @GetMapping
    @ApiOperation("查询接口角色分页")
    public R get(String id, String name) {
        Sqler sqler = new Sqler("t.id,t.name", table);
        sqler.addLeftJoin("o.name as crman", "sys_org o", "o.id=t.crmid");
        sqler.addLeftJoin("o2.name as upman", "sys_org o2", "o2.id=t.upmid");
        sqler.addSelect("t.crtim,t.uptim,t.notes");
        sqler.addLike("t.name", name);
        sqler.addLike("t.id", id);
        sqler.addOrder("t.crtim desc");
        return R.ok(jdbcDao.findPageData(sqler));
    }

    @GetMapping("perms")
    @ApiOperation("查询接口角色权限")
    public R getPerms(String id, String type) {
        String allSql = "SELECT r.id as \"id\",r.pid as \"pid\",r.name as \"name\",case when rr.id is null then null else 'true' end as \"checked\" FROM sys_api_main r LEFT JOIN sys_api_role_api rr ON rr.pid=r.id AND rr.id=? where r.cotag = 0 ";
        if ("all".equals(type)) {
            return R.ok(jdbcDao.findMapList(allSql, id));
        } else {
            allSql += " and r.pid like ?";
            return R.ok(jdbcDao.findMapList(allSql, id, type + "%"));
        }
    }

    @GetMapping("one/{id}")
    @ApiOperation("查询接口角色详情")
    public R getOne(@PathVariable String id) {
        SysApiRole main = service.findOne(id);
//        main.setPerms(null);
        return R.ok(main);
    }


    @PostMapping
    @ApiOperation("新增接口角色")
    public R post(@RequestBody SysApiRole main) {
        service.insert(main);
        userCacheService.reset();
        return R.ok();
    }

    @PutMapping
    @ApiOperation("修改接口角色")
    public R put(@RequestBody SysApiRole main) {
        service.update(main);
        userCacheService.reset();
        return R.ok();
    }

    @PostMapping("flush")
    @ApiOperation("刷新用户权限")
    public R flush() {
        userCacheService.reset();
        return R.ok();
    }

    @DeleteMapping("{ids}")
    @ApiOperation("删除接口角色")
    public R delete(@PathVariable String[] ids) {
        return R.ok(service.delete(ids));
    }

    @Autowired
    private JdbcDao jdbcDao;

    @Autowired
    private UserCacheService userCacheService;

    @Autowired
    private SysApiRoleService service;
}
